#include "bsp_gpt.h"

/*
fac:分频系数
OCR_number：哪个OCR寄存器
value：给OCR写入的比较值
*/
void GPT1_Init(uint16_t fac,int OCR_number,uint32_t value)
{
    GPT1->CR |= 1<<15;
    while(GPT1->CR & (1<<15));

    GPT1->CR =0;
    GPT1->CR|= (1<<1)|(1<<6);//使能从0开始计数，使用66MHZ分频

    GPT1->PR = fac;//分屏系数

    GPT1->OCR[OCR_number]=value;
}
void GPT1_ON()
{
    GPT1->CR |= 1<<0;
}
void GPT1_OFF()
{
    GPT1->CR &= ~(1<<0);
}
void Delay_Init()
{
    //1MHZ=1us计数1下,所以参数使用0xFFFFFFFF,一直延时到最大值
    GPT1_Init(65,0,0xFFFFFFFF);
    GPT1_ON();
}
void Delay_us(uint32_t us)
{
    uint32_t oldTime = GPT1->CNT , newTime = oldTime;
    uint32_t currentTime=0;
    while(1)
    {
        newTime = GPT1->CNT;
        if(newTime!=oldTime)
        {
            if(newTime>=oldTime)
                currentTime=newTime-oldTime;
            else
                currentTime=newTime+0xFFFFFFFF-oldTime;//eg:1+0xFFFFFFFF-2=0xFFFFFFFE,差1到最大值
                                                                                                            //单纯是一把尺子不够长，再拿一把，0刻度与最大刻度重合组合成长尺子
                                                                                                            //从数学看是0xFFFFFFFF减去一个负数
            if(currentTime>=us)
                break;
        }
    }
}
void Delay_ms(uint32_t ms)
{
    while(ms--)
    {
        Delay_us(1000);
    }
}